import global from '../js/global'
import {
  MessageBox,
  Message,
} from 'element-ui'; //element库的消息提示，可以不用

import Vue from 'vue';
import VueRouter from 'vue-router';

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter);
import routes from '../router/router.config.js'

const router = new VueRouter(routes)

export default {
  components: {},
  data() {
    return {
      allow: 1,
      date: '',
      type: '',
      cdn: 'http://static.shonemore.com/',
      pages: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      qnToken: {
        token: ''
      },
      title: {},
      query: {},
      item: {},
      select: [],
      one: [],
      two: [],
      province: [],
      city: [],
      area: [],
      data: [],
      imgList: [],
      status: '',
      qn_token: '',
      viewModal: false,
      videwIndex: '',
      img: '',
      src: '',
      editModal: false,
      previewModal: false,
      showFoot: false,
      img: '',
      preview_url: '',
      preview_list: [],
      defaultList: [],
      user_level: [{
        id: 2,
        name: '青铜'
      },
        {
          id: 3,
          name: '白银'
        },
        {
          id: 4,
          name: '黄金'
        },
        {
          id: 5,
          name: '钻石'
        },
      ],
      vip_type: [{
        id: 2,
        name: '内部会员'
      },
        {
          id: 3,
          name: '赠送会员'
        },
        {
          id: 4,
          name: '初始会员'
        },
        {
          id: 5,
          name: '正式会员'
        },
        {
          id: 6,
          name: '商家会员'
        }
      ],
      partner: [{
        id: 2,
        name: '初级团长'
      },
        {
          id: 3,
          name: '中级团长'
        },
        {
          id: 4,
          name: '高级团长'
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

    }
  },
  methods: {

    refreshPage() {
      let refresh = localStorage.getItem("refresh");
      if (!refresh) {
        console.log('refresh')
        router.go(0);
        localStorage.setItem("refresh", 1);
      }
    },
    uploadPoster(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.poster = e.key;
    },
    uploadPicture(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.picture = e.key;
    },
    uploadLogo(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.logo = e.key;
    },
    uploadCover(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.cover = e.key;
    },
    uploadPhoto(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.photo = [...this.item.photo, e.key];
    },


    uploadLicense(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.license = e.key;
    },
    uploadCertificate(e) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
      this.item.certificate = [...this.item.certificate, e.key];
    },
    removeVideo() {
      this.item.video = ''
    },

    // uploadVideo(e) {
    //   this.item.video = "https://cdn.shonemore.com/" + e.key;
    // },

    changePage(e) {
      sessionStorage.setItem(this.$route.name + "page", e);
      this.getTableData();
    },

    changeStatus(e) {
      this.query.status = e
      console.log(this.query.status)
      this.getTableData(true)
    },

    getDateRange(e) {
      this.query.start_at = e[0]
      this.query.end_at = e[1]
    },

    getPageData() {
      this.getData(true)
      this.getTrend()
    },
    reset() {
      this.query = {}
      this.getTableData(true)
    },

    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不支持",
        desc: "文件格式： " + file.name + " 不支持,请选择 jpg 或 png."
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件太大",
        desc: "" + file.name + " 太大, 不能超过2M."
      });
    },
    handleBeforeUpload() {
      return true;
    },
    hideModal(e) {
      console.log(e)
    },

    viewHandler(e) {
      this.visible = true
      this.src = e
    },


    preview(e, index, showFoot) {
      this.img = e;
      this.previewIndex = index
      this.previewModal = true
      this.showFoot = showFoot
    },

    setImgIndex(e) {
      let new_cover = this.item.photo[e]
      this.item.photo.splice(e, 1)
      this.item.photo.unshift(new_cover)
      this.previewModal = false
      this.$message({
        type: 'success',
        message: '设置成功'
      })
    },
    remove(e) {
      this.$confirm('是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.item.photo.splice(e, 1);
        this.$message({
          type: 'sucess',
          message: '已删除'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })

    },


    // preview(e,index){
    //   this.previewModal = true
    //   this.preview_list = e
    //   this.preview_url = e[index]
    // },

    handleSizeChange(e) {
      this.query.offset = e
      this.getData(true)
    },
    handleCurrentChange(e) {
      sessionStorage.setItem(this.$route.name + 'page', e)
      this.getData()
    },

    pageData(data) {
      this.tableData = data.data;
      this.pages.total = data.total;
      this.pages.currentPage = data.current_page;
      this.pages.per_page = data.per_page;
    },

    getData(flag = false) {
      if (this.is_page) {
        if (flag === true) {
          this.query.page = 1
        } else {
          let page = sessionStorage.getItem(this.$route.name + 'page')
          if (page) {
            this.query.page = page
          } else {
            this.query.page = 1
          }
        }
        global.httpRequest(this.api_url, this.query).then((res) => {
          this.pages.total = res.total
          this.pages.currentPage = res.current_page
          this.pages.per_page = res.per_page
          this.data = res.data
        });
      } else {
        global.httpRequest(this.api_url, this.query).then((res) => {
          this.data = res
        });
      }
    },

    getItem() {
      global.httpRequest(this.api_url, {
        id: this.item.id
      }).then((res) => {
        this.item = res
      });
    },

    getProvince() {
      global.httpRequest("area", {
        p_id: 0
      }).then((res) => {
        this.province = res
      });
    },


    getCity() {
      global.httpRequest("area", {
        p_id: this.query.province_id
      }).then((res) => {
        this.city = res;
      });
    },

    getArea() {
      global.httpRequest("area", {
        p_id: this.query.city_id
      }).then((res) => {
        this.area = res;
        this.query.area_id = ''
      });
    },

    getQueryCity() {
      global.httpRequest("area", {
        p_id: this.query.province_id
      }).then((res) => {
        this.city = res;
        this.query.city_id = ''
      });
    },

    getQueryArea() {
      global.httpRequest("area", {
        p_id: this.query.city_id
      }).then((res) => {
        this.area = res;
        this.query.area_id = ''
      });
    },

    getItemCity(flag = false) {
      global.httpRequest("area", {
        p_id: this.item.province_id
      }).then((res) => {
        this.city = res;
        if (flag) {
          this.area = []
        }
      });
    },


    getItemArea(flag = false) {
      global.httpRequest("area", {
        p_id: this.item.city_id
      }).then((res) => {
        if (flag) {
          this.item.area_list = []
        }
        this.area = res;
      });
    },

    setItemOne() {
      this.item.two_id = ''
      this.getItemTwo()
    },
    getItemTwo() {
      global
        .httpRequest("shop/cate", {
          p_id: this.item.one_id
        })
        .then((res) => {

          this.two = res;
        });
    },

    getQueryTwo() {
      global.httpRequest("shop/cate", {
        p_id: this.query.one_id
      }).then((res) => {
        this.two = res;
        this.query.two_id = ''
      });
    },


    edit() {
      console.log(this.item)
      let method = 'post'
      if (this.item.id) {
        method = 'put'
      }
      global.httpRequest(this.api_url, this.item, method).then((res) => {
        let {
          code
        } = res
        if (code == 0) {
          this.editModal = false
          this.getData()
        }
      });
    },
    del(e) {
      let that = this
      that.item = e
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        global.httpRequest(this.api_url, that.item, 'delete').then((res) => {
          let {
            code
          } = res
          if (code == 0) {

            this.getData()
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    reset() {
      this.query = {}
      this.getData(true)
    },

    getQnToken() {
      global.httpRequest('qnToken').then((res) => {
        this.qnToken.token = res
      });
    },

    getEchartOption(x = '', y = '', title = '') {

      let opton = {
        title: {
          text: title
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: x
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: y,
          type: 'line'
        }]
      }
      return opton
    },
    showWangEdit(e) {

      e.customConfig.menus = [
        "head",
        "bold",
        "italic",
        "justify",
        "fontSize",
        // 'video',
        "image"
      ];

      e.customConfig.uploadImgServer =
        "https://screw.shonemore.com/api/admin/wangUpload";
      e.customConfig.uploadFileName = "file[]"
      e.customConfig.uploadImgMaxLength = 5
      e.customConfig.showLinkImg = false
      e.customConfig.zIndex = 1000
      e.customConfig.onchange = html => {
        this.item.content = html;
      };
      // editor.txt.html();设置编辑器内容
      e.create();
      e.txt.html(this.item.content);
    },


  },
  created() {
  },
  mounted() {
    let currentPage = Number(localStorage.getItem('pagination')) || 1
    this.pages.pageNum = currentPage
  },

  beforeUpdate() {
    localStorage.setItem('pagination', this.pages.pageNum)
  },
  beforeDestroy() {
    let cachePage = ['spe', 'new', 'flower', 'team', 'hotFlower']
    let cachePage2 = ['newProDetail', 'orderList', 'orderDetail']
    this.$router.beforeEach((to, from, next) => {
      if (!cachePage2.includes(to.name) && (!cachePage2.includes(from.name) || !cachePage.includes(to.name))) {
        // console.log(to.name, from.name, cachePage.includes(to.name))
        localStorage.setItem('lastPage', from.name)
        localStorage.setItem('pagination', '1')
      }
      next()
    })
  },
  computed: {
    systemMap() {
      return this.$store.getters.systemMap
    }
  }
}
